const express = require('express')
const router = express.Router()
const pool = require('../../db/db')
const Response = require('../../utils/ResponseData')

/**
 * 新增宠物接口
 * url: http://localhost:3000/pet/add
 */
router.post('/add', (req, res, next) => {
    console.log(req.body);
    let {uid} = req.user
    // 获取前端请求信息
    let { pImg, pName, pYear, pGender,pType, pContent, pBreed } = req.body
    const sql = `insert into pet(p_img,p_name,p_year,p_gender,p_type,p_content,p_breed,user_id) value(?,?,?,?,?,?,?,?)`
    pool.query(sql,[pImg,pName,pYear,pGender,pType,pContent,pBreed,uid],(err,result) =>{
        if(err) {
            console.log('/pet/add',err)
            next(err)
            return
        }
        if(result.affectedRows > 0) {
            res.send(Response.success(null,'宠物添加成功！'))
        } else{
            res.send(Response.error('宠物添加失败！'))
        }
    })
})  

/**
 * 宠物列表获取
 */
router.get('/getAll',(req,res,next) =>{
    let {uid} = req.user
    const sql = `select * from pet where user_id=?`
    pool.querySync(sql,[uid])
        .then(result => {
            if(result.length > 0) {
                res.send(Response.success({
                    data:result,
                    total: result.length,
                },'宠物列表数据获取成功！'))
            } else {
                res.send(Response.error('宠物列表获取失败！'))
            }
        }).catch(err => {
            if(err) {
                console.log('/pet/getAll',err);
                next(err)
                return
            }
        })
})

module.exports = router